package com.example.android

import android.content.Context
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.embedding.engine.dart.DartExecutor

object FlutterMgr {
    const val ENGINE_ID: String = "default_engine_id"

    const val ROUTE_PAGE_DEFAULT: String = "/"
    const val ROUTE_PAGE_A: String = "/page_a"
    const val ROUTE_PAGE_B: String = "/page_b"
    const val ROUTE_PAGE_TEST_METHOD_CHANNEL: String = "/page_test_method_channel"
    const val ROUTE_PAGE_LIFECYCLEWATCHER: String = "/LifecycleWatcher"


    private var sFlutterEngine: FlutterEngine? = null

    fun preWarmFlutterEngine(context: Context) {
        if (null == sFlutterEngine) {
            sFlutterEngine = FlutterEngine(context)
            sFlutterEngine!!.dartExecutor.executeDartEntrypoint(
                DartExecutor.DartEntrypoint.createDefault()
            )
            MethodChannelMgr.init(sFlutterEngine!!.dartExecutor)
            MyEventChannel(sFlutterEngine!!.dartExecutor)
            FlutterEngineCache.getInstance().put(ENGINE_ID, sFlutterEngine)
        }
    }

    @JvmStatic
    fun setInitRoute(route: String?) {
        MethodChannelMgr.callFlutter("setInitRoute", route)
    }

    fun destroyEngine() {
        if (sFlutterEngine != null) {
            sFlutterEngine!!.destroy()
        }
    }
}
